package com.net.wheels.copier;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.net.common.util.NameUtil;

/**
 * Created by  on 2016/1/13.
 * 对象属性值的复制
 */
public class DomainCopier {
    public static void main(String[] args) throws Exception {
        DomainCopier copier = new DomainCopier();
        //copier.copy(User.class, "user", "userInfoDto");
        //copier.set(AccountBill.class, "accountBill");
        //copier.fields(User.class);
        //copier.toJson(AcceptModel.class);
    }

    void toJson(Class clazz) {
        List<String> orderedNames = getClassNames(clazz);
        StringBuilder buffer = new StringBuilder();

        buffer.append("{\n");
        for (String name : orderedNames) {
            buffer.append("  \"").append(name).append("\" : ,");
            buffer.append("\n");
        }
        String str = buffer.substring(0, buffer.length() - 2);
        str = str + ("\n}");

        System.out.println(str);
    }

    void copy(Class clazz, String newName, String oldName) {
        List<String> orderedNames = getClassNames(clazz);
        StringBuilder buffer = new StringBuilder();

        for (String name : orderedNames) {
            buffer.append("    ").append(newName).append(".set").append(upperFirstChar(name));
            buffer.append("(").append(oldName).append(".get").append(upperFirstChar(name)).append("());");
            buffer.append("\n");
        }
        System.out.println(buffer.toString());
    }

    public void set(Class clazz, String newName) {
        List<String> orderedNames = getClassNames(clazz);
        StringBuilder buffer = new StringBuilder();

        for (String name : orderedNames) {
            buffer.append("    ").append(newName).append(".set").append(upperFirstChar(name));
            buffer.append("();");
            buffer.append("\n");
        }
        System.out.println(buffer.toString());
    }

    public void fields(Class clazz) {
        List<String> orderedNames = getClassNames(clazz);
        StringBuilder buffer = new StringBuilder();

        for (String name : orderedNames) {
            buffer.append(NameUtil.camelToUnderline(name)).append(", ");
        }
        System.out.println(buffer.toString());
    }

    private String upperFirstChar(String str) {
        char ch = str.charAt(0);
        String endStr = str.substring(1);
        return Character.toUpperCase(ch) + endStr;
    }

    private List<String> getClassNames(Class clazz) {
        Field fields[] = clazz.getDeclaredFields(); // 取得全部的变量     不包括接口的属性
        List<String> orderedNames = new ArrayList<>();
        for (Field f : fields) {
            orderedNames.add(f.getName());
        }
        return orderedNames;
    }
}
